package cn.com.chengmandian.bike.controller;


import cn.com.chengmandian.agent.utils.AuthUtil;
import cn.com.chengmandian.bike.dto.MemberLifeCheckForm;
import cn.com.chengmandian.bike.dto.MemberLifeInitForm;
import cn.com.chengmandian.bike.model.EbMemberLife;
import cn.com.chengmandian.bike.pojo.UserCodeInfo;
import cn.com.chengmandian.bike.service.IEbMemberLifeService;
import cn.com.chengmandian.core.common.constants.CommonConstant;
import cn.com.chengmandian.core.redis.service.RedisService;
import cn.com.chengmandian.core.web.pojo.AgentInfo;
import cn.com.chengmandian.core.web.pojo.AgentUser;
import cn.com.chengmandian.core.web.pojo.AjaxResult;
import cn.com.chengmandian.core.web.utils.LocalMapUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 电单车运营-活体检测记录 前端控制器
 * </p>
 *
 * @author AutoGenerator
 * @since 2024-06-24
 */
@Api(tags = "活体检测记录")
@RestController
@RequestMapping("/member/life")
public class EbMemberLifeController {

    @Autowired
    private IEbMemberLifeService memberLifeService;

    @Autowired
    private RedisService redisService;

    @ApiOperation("初始化(无需登录)")
    @PostMapping("/init")
    public AjaxResult<EbMemberLife> init(@RequestBody MemberLifeInitForm form) {
        Assert.isTrue(StrUtil.isNotBlank(form.getReturnUrl()), "缺少检测完成后页面自动重定向地址");
        Assert.isTrue(StrUtil.isNotBlank(form.getName()), "缺少姓名");
        Assert.isTrue(StrUtil.isNotBlank(form.getIdCard()), "缺少身份证号");
        AgentUser agentUser = AuthUtil.getAgentUser();
        AgentInfo agentInfo = LocalMapUtil.getAgentInfo();
        Integer memberId = null;
        String mobile = null;
        if (agentUser == null) {
            String key = "CMD:BIKE:"+ agentInfo.getId() + ":USERCODE:" + form.getUserCode();
            Assert.isTrue(redisService.hasKey(key), "缺少注册信息");
            UserCodeInfo userCodeInfo = (UserCodeInfo) redisService.get(key);
            mobile = userCodeInfo.getMobile();
        } else {
            memberId = agentUser.getId();
        }

        return AjaxResult.success(memberLifeService.initLifeCheck(agentInfo, CommonConstant.ONE, memberId, mobile, form.getReturnUrl(), form.getColors(), form.getActions(), form.getName(), form.getIdCard()));
    }

    @ApiOperation("检测(无需登录)")
    @PostMapping("/check")
    public AjaxResult<EbMemberLife> check(@RequestBody MemberLifeCheckForm form) {
        Assert.isTrue(StrUtil.isNotBlank(form.getToken()), "缺少活体检测TOKEN");

        return AjaxResult.success(memberLifeService.startLifeCheck(form.getToken(), LocalMapUtil.getAgentInfo()));
    }
}
